"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm

from pacp.model import meta
from pacp.lib.pipetech import RUNS_FLDS, DETAILS_FLDS, DETAILS, RUNS

#globals
run_flds = RUNS_FLDS

detail_flds = DETAILS_FLDS

def init_model(engine):
    """Call me before using any of the tables or classes in the model"""
    ## Reflected tables must be defined and mapped here
    #global reflected_table
    details_table_args = ["Details", meta.metadata, 
                             sa.schema.Column('DetailID', sa.types.Integer, primary_key=True), 
                             sa.schema.Column('RunID', sa.types.Integer, sa.schema.ForeignKey('Runs.RunID'))]
    for k, v in DETAILS.items():
        if len(v)>2 and v[2] in ['PK', 'FK']:
            pass
        else:
            details_table_args.append(sa.schema.Column(k, getattr(sa.types, v[0])))
    
    

#    details_table = sa.Table("Details", meta.metadata, 
#                             sa.schema.Column('DetailID', sa.types.Integer, primary_key=True), 
#                             sa.schema.Column('RunID', sa.types.Integer, sa.schema.ForeignKey('Runs.RunID')),                              
#                             autoload=True,
#                               autoload_with=engine)

    print details_table_args
    details_table = sa.Table(*details_table_args)
    
    orm.mapper(Details, details_table)
    
    run_table_args = ["Runs", meta.metadata,
                         sa.schema.Column('RunID', sa.types.Integer, primary_key=True)]
    
    for k, v in RUNS.items():
        if len(v)>2 and v[2] in ['PK', 'FK']:
            pass
        else:
            run_table_args.append(sa.schema.Column(k, getattr(sa.types, v[0])))
    
#    
#    
#    run_table = sa.Table("Runs", meta.metadata,
#                         sa.schema.Column('RunID', sa.types.Integer, primary_key=True), 
#                         
#                          autoload=True,                        
#                               autoload_with=engine)
#    
    run_table = sa.Table(*run_table_args)
    orm.mapper(Run, run_table, properties={'details': orm.relation(Details, backref='Runs')})

    
    meta.Session.configure(bind=engine)
    meta.engine = engine
    



## Non-reflected tables may be defined and mapped at module level
#foo_table = sa.Table("Foo", meta.metadata,
#    sa.Column("id", sa.types.Integer, primary_key=True),
#    sa.Column("bar", sa.types.String(255), nullable=False),
#    )
#
#class Foo(object):
#    pass
#
#orm.mapper(Foo, foo_table)


## Classes for reflected tables may be defined here, but the table and
## mapping itself must be done in the init_model function
#reflected_table = None
#
#class Reflected(object):
#    pass
class Details(object):
        pass
class Run(object):
        pass